package com.fattiger.framework.sessionshare.session.redis;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.fattiger.framework.sessionshare.session.AbstractSessionManager;
import com.fattiger.framework.sessionshare.session.Session;
import com.fattiger.framework.util.ObjectUtils;
import com.fattiger.framework.util.RedisClient;
import com.fattiger.framework.util.StringUtils;

public class RedisSessionManager extends AbstractSessionManager {
    @Override
    public Session getSession(HttpServletRequest request, boolean create) throws IOException {
        String sessionId = getSessionIdFromCookie(request);
        if(create){
            if(!StringUtils.isEmpty(sessionId)){
                RedisClient.removeCache(ObjectUtils.object2Bytes(sessionId));
            }
            return new RedisSession(generateSessionId(),getSessionExpire(request));
        }else if(!StringUtils.isEmpty(sessionId)){
            if(RedisClient.exist(ObjectUtils.object2Bytes(sessionId))){
                RedisSession session = new RedisSession(sessionId,getSessionExpire(request));
                return session;
            }
            return null;
        }
        return null;
    }
}
